<!DOCTYPE HTML>
<html lang="cn" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
  <%include("/common/header.html",{title:''}){}%>
  <title>项目管理</title>
  <style>
  </style>
</head>
<body>

<div class="x-nav" style="margin: 20px auto auto 15px;">
      <span class="layui-breadcrumb" lay-filter="breadcrumb" style="visibility: visible;">
        <a href="javascript:">首页</a><span lay-separator="">/</span>
        <a href="javascript:">项目管理</a><span lay-separator="">/</span>
        <a><cite>项目管理</cite></a>
      </span>
  <a class="layui-btn layui-btn-primary layui-btn-small" style="margin: -5px 14px 0px 0px;float:right;"
     href="javascript:location.replace(location.href);" title="刷新">
    <i class="layui-icon layui-icon-refresh-3"></i>
  </a>
</div>

<div class="x-body" style="margin: 20px auto auto 15px;">
  <div class="layui-row">
    <div class="layui-btn-group">
      <button class="layui-btn" id="btn-expand">全部展开</button>
      <button class="layui-btn" id="btn-fold">全部折叠</button>
    </div>
  </div>
  <div class="layui-table-main layui-form" style="height: 100%;width: 98%;">
    <table id="auth-table" class="layui-table" lay-filter="auth-table"></table>
  </div>
</div>

<script type="text/html" id="myToolbarDemo">
  <div class="layui-btn-container">
    <a class="layui-btn layui-btn layui-btn-sm" lay-event="addone"><i class="layui-icon layui-icon-add-1"></i>添加场地</a>

  </div>
</script>
<!-- 操作列 -->
<script type="text/html" id="oper-col">
  {{#  if(d.parentId==-1){ }}
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="add">添加区域</a>
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  {{#  } }}


  {{#  if(d.parentId!=-1){ }}
  <a class="layui-btn layui-btn-xs" lay-event="areaedit">编辑</a>
  {{#  } }}
  <!--  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>-->
</script>

<!-- 弹出页面 -->
<div class="layui-form" lay-filter="layuiadmin-form-useradmin"
     id="layuiadmin-form-useradmin"
     style="padding: 15px;display: none">
  <form action class="layui-form" lay-filter="component-form-element" id="myform">
    <input type="hidden" name="id">
    <input type="hidden" id="pid" name="pid">
    <div class="layui-form-item" style="padding-left: 10px;">
      <div class="layui-input-inline">
        <input type="text" name="projectName" lay-verify="required" value="" class="layui-input"
               placeholder="请输项目名称">
      </div>
      <div class="layui-input-inline">
        <input type="text" name="managername" lay-verify="required" value="" class="layui-input"
               placeholder="请输项目经理名称">
      </div>

    </div>
    <div class="layui-form-item" style="padding-left: 10px;">
      <div class="layui-input-inline">
        <input type="text" name="contact" lay-verify="required" value="" class="layui-input"
               placeholder="请输联系方式">
      </div>
      <div class="layui-input-inline">
        <input type="text" name="remks" lay-verify="required" value="" class="layui-input"
               placeholder="请输项目介绍">
      </div>

    </div>

    <div class="layui-form-item" style="padding-left: 10px;">
      <div class="layui-input-inline">
        <input type="text" name="opentime" autocomplete="off" id="startTime" lay-verify="required" value=""
               class="layui-input"
               placeholder="选择项目开始时间">
      </div>
      <div class="layui-input-inline">
        <input type="text" name="endtime" autocomplete="off" id="endTime" lay-verify="required" value=""
               class="layui-input"
               placeholder="选择项目结束时间">
      </div>

    </div>
    <!--<div class="layui-form-item">
      <label class="layui-form-label" style="padding-left: 0px;font-size: medium;width: auto;">请输入轮播图内容:</label>
      <div class="layui-input-inline" style="width: 555px">
        <textarea id="content" type="text" style="display: none" name="content" lay-verify="content"></textarea>
      </div>
    </div>-->


    <div class="layui-form-item">
      <div class="layui-input-block" style="margin: 20px auto;width: max-content;">
        <button class="layui-btn" lay-submit="" lay-filter="component-form-element">立即提交</button>
      </div>
    </div>
  </form>
</div>

<%include("/common/foot.html"){}%>
<script>
  $(function () {
    var $ = layui.$;
    var title = "项目添加";
    var size = ['50%', '70%'];
    layui.config({
      base: 'static/layuiadmin'
    }).extend({
      treetable: '/modules/treetable'
    }).use(['layer', 'form', 'table', 'treetable', 'laydate'], function () {
      var $ = layui.jquery;
      var table = layui.table;
      var laydate = layui.laydate;
      var form = layui.form;
      var treetable = layui.treetable;

      var findAll_url = 'system/project/findAll.json';
      var update_url = 'system/project/update.jhtml';
      var addOne_url = 'system/project/addOne.jhtml';
      var delete_url = 'system/project/delete.jhtml';
      // 渲染表格
      var renderTable = function () {
        layer.load(2);
        treetable.render({
          treeColIndex: 1,
          treeSpid: -1,
          treeIdName: 'id',
          treePidName: 'parentId',
          treeDefaultClose: false,
          treeLinkage: false,
          toolbar: '#myToolbarDemo',
          elem: '#auth-table',
          url: findAll_url,
          page: false,
          cols: [[
            {type: 'numbers'},
            {field: 'projectName', title: '名称'},
            // {field: 'managername', title: '负责人'},
            {
              align: 'center', templet: function (d) {
                if (d.parentId == -1) {
                  return '<span class="layui-badge layui-bg-blue">场地</span>';
                } else {
                  return '<span class="layui-badge-rim">区域</span>';
                }
              }, title: '类型'
            },
            {templet: '#oper-col', align: 'center', title: '操作'}
          ]],
          done: function () {
            layer.closeAll('loading');
          }
        });
      };

      renderTable();


      //监听工具条
      table.on('tool(auth-table)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'add') {
          layer.prompt({title: '添加区域', formType: 3}, function (text, index) {
            layer.close(index);
            $.ajax({
              url: addOne_url,
              type: "POST",
              data: {
                "pid": data.id,
                "name": text,
              },
              dataType: "json",
              success: function (ret) {
                layer.msg(ret.msg, {icon: 6});
                setTimeout(function () {

                  window.location.reload();
                }, 1000);
              },
              error: function (jqXHR, textStatus, errorThrown) {
                var estr = "Page:" + window.location.pathname + ",Function: postDelete()";
                layer.open({
                  title: "错误信息",
                  area: ['600px', '600px'],
                  type: 2,
                  content: "base/error.jhtml?info=" + estr, //
                  btn: ['关闭'] //可以无限个按钮
                });
              }
            });
          })
        } else if (layEvent === 'edit') {
          layer.prompt({title: '修改场地', formType: 3, value: data.projectName}, function (text, index) {
            layer.close(index);
            $.ajax({
              url: update_url,
              type: "POST",
              data: {
                "name": text,
                "id": data.id,
              },
              dataType: "json",
              success: function (ret) {
                layer.msg(ret.msg, {icon: 6});
                setTimeout(function () {

                  window.location.reload();
                }, 1000);
              },
              error: function (jqXHR, textStatus, errorThrown) {
                var estr = "Page:" + window.location.pathname + ",Function: postDelete()";
                layer.open({
                  title: "错误信息",
                  area: ['600px', '600px'],
                  type: 2,
                  content: "base/error.jhtml?info=" + estr, //
                  btn: ['关闭'] //可以无限个按钮
                });
              }
            });
          })
          // initUpdate(data);
        } else if (layEvent === 'del') {
          layer.confirm('删除以后数据将不能恢复，确定删除吗？', function (index) {
            postDelete(data.id);
          });
        } else if (layEvent === 'areaedit') {
          layer.prompt({title: '添加区域', formType: 3, value: data.projectName}, function (text, index) {
            layer.close(index);
            $.ajax({
              url: addOne_url,
              type: "POST",
              data: {
                "name": text,
                "id": data.id,
              },
              dataType: "json",
              success: function (ret) {
                layer.msg(ret.msg, {icon: 6});
                setTimeout(function () {

                  window.location.reload();
                }, 1000);
              },
              error: function (jqXHR, textStatus, errorThrown) {
                var estr = "Page:" + window.location.pathname + ",Function: postDelete()";
                layer.open({
                  title: "错误信息",
                  area: ['600px', '600px'],
                  type: 2,
                  content: "base/error.jhtml?info=" + estr, //
                  btn: ['关闭'] //可以无限个按钮
                });
              }
            });
          })
        }
      });

      //监听工具条
      table.on('toolbar(auth-table)', function (obj) {
        var data = obj.config.data;
        var layEvent = obj.event;
        if (layEvent === 'addone') {
          layer.prompt({title: '添加场地', formType: 3}, function (text, index) {
            layer.close(index);
            $.ajax({
              url: update_url,
              type: "POST",
              data: {
                "name": text,
              },
              dataType: "json",
              success: function (ret) {
                layer.msg(ret.msg, {icon: 6});
                setTimeout(function () {

                  window.location.reload();
                }, 1000);
              },
              error: function (jqXHR, textStatus, errorThrown) {
                var estr = "Page:" + window.location.pathname + ",Function: postDelete()";
                layer.open({
                  title: "错误信息",
                  area: ['600px', '600px'],
                  type: 2,
                  content: "base/error.jhtml?info=" + estr, //
                  btn: ['关闭'] //可以无限个按钮
                });
              }
            });

          })

        }
      });

      //监听操作栏
      table.on('toolbar(oper-col)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

      });

      //弹出修改页面调用初始化数据方法
      function initUpdate(data) {
        layer.open({
          type: 1
          , area: ['100%', '100%']
          , content: $("#layuiadmin-form-useradmin")
        });
        //如果是添加则重置表单，如果是编辑则给表单赋值
        if (data == 0 || data == null) {
          $('#myform')[0].reset();

        } else {
          if (data.parentId != -1) {
            $('#qwe').hide();
          } else {
            $('#qwe').show();
          }
          layui.form.val("component-form-element", loadData(data));
        }
      }

      //图片上传
      // AliangLayui.layuiImagepost("#upload1", "#img1");
      layui.use('upload', function () {
        var $ = layui.jquery, upload = layui.upload;
        var uploadInst = upload.render({
          elem: '#upload1',
          auto: false,
          choose: function (obj) {
            obj.preview(function (index, file, result) {//预读本地文件示例，不支持ie8
              console.log(JSON.stringify(obj));
              console.log(JSON.stringify(file));
              $('#img1').attr('src', result); //图片链接（base64）
            });
            //alert(img1.result)
          }
        });
      });

      $('#btn-expand').click(function () {
        treetable.expandAll('#auth-table');
      });
      $('#btn-fold').click(function () {
        treetable.foldAll('#auth-table');
      });


      //修改页面的内容提交到后台处理
      form.on('submit(component-form-element)', function (data) {
        // data.field.content = layedit.getContent(index);
        postUpdate(data);
        return false;
      });

      //验证通过后提交数据到后台
      form.on('submit(submission)', function (data) {
        /*       layer.alert(JSON.stringify(data.field), {
                   title: '最终的提交信息'
               });*/
        postUpdate(data);
        return false;
      });

      //初始化修改页面
      function loadData(data) {
        var ret = {
          "id": data.id,
          "pid": data.parentId,
          "projectName": data.projectName,
          "managername": data.managername,
          "contact": data.contact,
          "opentime": data.opentime,
          "endtime": data.endtime,
          "remks": data.remks
        };
        $("#img1").attr("src", data.picture);
        return ret;
      }

      //ajax提交修改内容
      window.postUpdate = function (data) {
        var formData = new FormData();
        formData.append("data", JSON.stringify(data.field));
        $.ajax({
          url: update_url,
          type: "POST",
          //traditional:true,
          data: formData,
          processData: false,
          contentType: false,
          success: function (data) {
            if (data.code == 0) {
              layer.closeAll();
              layer.msg(data.msg, {time: 600, icon: 1}, function () {
                //table.reload('listReload');
                location.replace(location.href);
              });
            } else {
              layer.msg(data.msg, {icon: 5});
            }
          },
          error: function (jqXHR, textStatus, errorThrown) {
            var estr = "Page:" + window.location.pathname + ",Function:postUpdate()";
            layer.open({
              title: "错误信息",
              type: 2,
              content: "base/error.jhtml?info=" + estr,
              btn: ['关闭'] //可以无限个按钮
            });
          }
        });
      };

      //ajax提交删除内容
      window.postDelete = function (id) {
        $.ajax({
          url: delete_url,
          type: "POST",
          data: {
            "id": id
          },
          dataType: "json",
          success: function (ret) {
            if (ret == null) {
              layer.msg("删除失败", {
                icon: 5
              });
            } else {
              if (ret.code == 0) {
                layer.msg("当前分类下拥有商品信息，请先删除相关商品", {
                  icon: 5
                });
              } else if (ret.code == 1) {
                layer.msg("删除成功", {
                  icon: 6
                });
                layer.closeAll();
                window.location.reload();
              }
            }
            return ret;
          },
          error: function (jqXHR, textStatus, errorThrown) {
            var estr = "Page:" + window.location.pathname + ",Function: postDelete()";
            layer.open({
              title: "错误信息",
              area: ['600px', '600px'],
              type: 2,
              content: "base/error.jhtml?info=" + estr, //
              btn: ['关闭'] //可以无限个按钮
            });
          }
        });
      };

      //执行laydate
      var startDate = laydate.render({
        elem: '#startTime', //指定元素
        done: function (value, date) {
          // 结束时间大于开始时间
          if (value !== '') {
            endDate.config.min.year = date.year;
            endDate.config.min.month = date.month - 1;
            endDate.config.min.date = date.date;
          } else {
            endDate.config.min.year = '';
            endDate.config.min.month = '';
            endDate.config.min.date = '';
          }
        }
      });
      //执行laydate
      var endDate = laydate.render({
        elem: '#endTime', //指定元素
        done: function (value, date) {
          //  开始时间小于结束时间
          if (value !== '') {
            startDate.config.max.year = date.year;
            startDate.config.max.month = date.month - 1;
            startDate.config.max.date = date.date;
          } else {
            startDate.config.max.year = '';
            startDate.config.max.month = '';
            startDate.config.max.date = '';
          }
        }
      });

    });


  })

</script>
</body>

</html>
